import logging
import util.dtest
import test.utils
import test.neon_support as ns

print '''Test of 2 nodes, each sending some amount of data between
them using TCP.'''

dtest = util.dtest.DTest()
cond = ns.Conditions(dtest)

node_a = dtest.add_node(ns.NeonNode('A'))
node_b = dtest.add_node(ns.NeonNode('B'))

# Create link between A <-> B
node_a_in = node_a.reg_tx_tcp_in()
node_b.reg_tx_tcp_out(node_a_in, 1)

dtest.set_mapper(util.dtest.LocalMapper())

dtest.configure()
dtest.setup_files()

def test_script(tr):
    node_a.run_tx()
    node_b.run_tx()
    
    tr.wait_for(5, cond.on_all(cond.tx_is_running))
    tr.wait_for(5, cond.channel_state, 'A', 'tcp/0', 'B', 'handshake')
    tr.wait_for(5, cond.channel_state, 'B', 'tcp/0', 'A', 'handshake')

    s_a = node_a.tx_api_sock()
    s_b = node_b.tx_api_sock()
    l = test.utils.sock_readln(s_a)
    assert l == 'h B tcp/0'
    l = test.utils.sock_readln(s_b)
    assert l == 'h A tcp/0'
    s_a.send('h B tcp/0 hello\n')
    s_b.send('h A tcp/0 world\n')

    tr.wait_for(5, cond.channel_state, 'A', 'tcp/0', 'B', 'connected')
    tr.wait_for(5, cond.channel_state, 'B', 'tcp/0', 'A', 'connected')

    # XXX/bowei -- is next part non-deterministic?
    l = test.utils.sock_readln(s_a)
    assert l == 'H B tcp/0 world'    
    l = test.utils.sock_readln(s_b)
    assert l == 'H A tcp/0 hello'

    l = test.utils.sock_readln(s_a)
    assert l == 'd B tcp/0'    
    l = test.utils.sock_readln(s_b)
    assert l == 'd A tcp/0'

    s_a.send('d B tcp/0 data\n')
    s_b.send('d A tcp/0 atad\n')
    
    l = test.utils.sock_readln(s_a)
    assert l == 'D B atad' or l == 'd B tcp/0'
    l = test.utils.sock_readln(s_a)
    assert l == 'D B atad' or l == 'd B tcp/0'

    l = test.utils.sock_readln(s_b)
    assert l == 'D A data' or l == 'd A tcp/0'
    l = test.utils.sock_readln(s_b)
    assert l == 'D A data' or l == 'd A tcp/0'
    
dtest.run(test_script)
